﻿

using COVID_19_LiquidFillUI.Models;
using HalconDotNet;
using NLog;
using System.Collections.ObjectModel;
using System;
using ViewROI;
using Prism.Services.Dialogs;
using System.Linq;
using System.IO;
using System.Windows.Forms;
using MessageBox = System.Windows.Forms.MessageBox;
using DialogResult = System.Windows.Forms.DialogResult;
using System.Collections.Generic;
using COVID_19_LiquidFillUI.Common.Services;
using Prism.Ioc;
using Microsoft.EntityFrameworkCore.Metadata.Internal;

namespace COVID_19_LiquidFillUI.ViewModels.Dialogs
{
    public class Station2CameraCalcDialogViewModel : DialogViewModel
    {
        #region 变量
        ICameraService cam;
        int cameraIndex = 0;
        private static Logger logger = LogManager.GetCurrentClassLogger();
        private readonly IContainerProvider _containerProvider;
        private List<MJudgeCalc> mJudgeCalcList= new List<MJudgeCalc>();
        #endregion
        #region 属性绑定
        #region halcon
        #region 1#
        private HImage cameraIamge0;
        public HImage CameraIamge0
        {
            get { return cameraIamge0; }
            set { SetProperty(ref cameraIamge0, value); }
        }
        private bool cameraRepaint0;
        public bool CameraRepaint0
        {
            get { return cameraRepaint0; }
            set { SetProperty(ref cameraRepaint0, value); }
        }
        private ObservableCollection<ROI> cameraROIList0 = new ObservableCollection<ROI>();
        public ObservableCollection<ROI> CameraROIList0
        {
            get { return cameraROIList0; }
            set { SetProperty(ref cameraROIList0, value); }
        }
        private HObject cameraAppendHObject0;
        public HObject CameraAppendHObject0
        {
            get { return cameraAppendHObject0; }
            set { SetProperty(ref cameraAppendHObject0, value); }
        }
        private HMsgEntry cameraAppendHMessage0;
        public HMsgEntry CameraAppendHMessage0
        {
            get { return cameraAppendHMessage0; }
            set { SetProperty(ref cameraAppendHMessage0, value); }
        }
        private Tuple<string, object> cameraGCStyle0;
        public Tuple<string, object> CameraGCStyle0
        {
            get { return cameraGCStyle0; }
            set { SetProperty(ref cameraGCStyle0, value); }
        }
        #endregion
        #endregion
        private int thresholdMin;
        public int ThresholdMin
        {
            get { return thresholdMin; }
            set { SetProperty(ref thresholdMin, value); }
        }
        private int tresholdMax;
        public int ThresholdMax
        {
            get { return tresholdMax; }
            set { SetProperty(ref tresholdMax, value); }
        }
        private int judgeArea;
        public int JudgeArea
        {
            get { return judgeArea; }
            set { SetProperty(ref judgeArea, value); }
        }
        private ObservableCollection<DispVisionPoint2> pointList1;
        public ObservableCollection<DispVisionPoint2> PointList1
        {
            get { return pointList1; }
            set { SetProperty(ref pointList1, value); }
        }
        private int measureThrehold;
        public int MeasureThrehold
        {
            get { return measureThrehold; }
            set { SetProperty(ref measureThrehold, value); }
        }
        private double sT_RadiusMin;
        public double ST_RadiusMin
        {
            get { return sT_RadiusMin; }
            set { SetProperty(ref sT_RadiusMin, value); }
        }
        private double sT_RadiusMax;
        public double ST_RadiusMax
        {
            get { return sT_RadiusMax; }
            set { SetProperty(ref sT_RadiusMax, value); }
        }
        private ObservableCollection<DispMDrawCircle> circleList1;
        public ObservableCollection<DispMDrawCircle> CircleList1
        {
            get { return circleList1; }
            set { SetProperty(ref circleList1, value); }
        }
        private int circleIndex0;
        public int CircleIndex0
        {
            get { return circleIndex0; }
            set { SetProperty(ref circleIndex0, value); }
        }
        private int circleIndex1;
        public int CircleIndex1
        {
            get { return circleIndex1; }
            set { SetProperty(ref circleIndex1, value); }
        }
        private double sT_DistMin;
        public double ST_DistMin
        {
            get { return sT_DistMin; }
            set { SetProperty(ref sT_DistMin, value); }
        }
        private double sT_DistMax;
        public double ST_DistMax
        {
            get { return sT_DistMax; }
            set { SetProperty(ref sT_DistMax, value); }
        }
        private ObservableCollection<DispMJudge> judgeList1;
        public ObservableCollection<DispMJudge> JudgeList1
        {
            get { return judgeList1; }
            set { SetProperty(ref judgeList1, value); }
        }
        private double modelThresholdMax;
        public double ModelThresholdMax
        {
            get { return modelThresholdMax; }
            set { SetProperty(ref modelThresholdMax, value); }
        }
        #endregion
        #region 方法绑定
        private DelegateCommand<object> cameraOperateCommand;
        public DelegateCommand<object> CameraOperateCommand =>
            cameraOperateCommand ?? (cameraOperateCommand = new DelegateCommand<object>(ExecuteCameraOperateCommand));
        private DelegateCommand<DispVisionPoint2> pointList1SelectCommand;
        public DelegateCommand<DispVisionPoint2> PointList1SelectCommand =>
            pointList1SelectCommand ?? (pointList1SelectCommand = new DelegateCommand<DispVisionPoint2>(ExecutePointList1SelectCommand));
        private DelegateCommand<DispVisionPoint2> createRec1Command;
        public DelegateCommand<DispVisionPoint2> CreateRec1Command =>
            createRec1Command ?? (createRec1Command = new DelegateCommand<DispVisionPoint2>(ExecuteCreateRec1Command));
        private DelegateCommand<DispVisionPoint2> updateCommand;
        public DelegateCommand<DispVisionPoint2> UpdateCommand =>
            updateCommand ?? (updateCommand = new DelegateCommand<DispVisionPoint2>(ExecuteUpdateCommand));
        private DelegateCommand calcCommand;
        public DelegateCommand CalcCommand =>
            calcCommand ?? (calcCommand = new DelegateCommand(ExecuteCalcCommand));
        private DelegateCommand posImageCreateRegionCommand;
        public DelegateCommand PosImageCreateRegionCommand =>
            posImageCreateRegionCommand ?? (posImageCreateRegionCommand = new DelegateCommand(ExecutePosImageCreateRegionCommand));
        private DelegateCommand posImageFindModelCommand;
        public DelegateCommand PosImageFindModelCommand =>
            posImageFindModelCommand ?? (posImageFindModelCommand = new DelegateCommand(ExecutePosImageFindModelCommand));
        private DelegateCommand posImageSetStandardCommand;
        public DelegateCommand PosImageSetStandardCommand =>
            posImageSetStandardCommand ?? (posImageSetStandardCommand = new DelegateCommand(ExecutePosImageSetStandardCommand));
        private DelegateCommand<DispMDrawCircle> circleList1SelectCommand;
        public DelegateCommand<DispMDrawCircle> CircleList1SelectCommand =>
            circleList1SelectCommand ?? (circleList1SelectCommand = new DelegateCommand<DispMDrawCircle>(ExecuteCircleList1SelectCommand));
        private DelegateCommand<DispMDrawCircle> updateCircleCommand;
        public DelegateCommand<DispMDrawCircle> UpdateCircleCommand =>
            updateCircleCommand ?? (updateCircleCommand = new DelegateCommand<DispMDrawCircle>(ExecuteUpdateCircleCommand));
        private DelegateCommand<DispMDrawCircle> createCircleCommand;
        public DelegateCommand<DispMDrawCircle> CreateCircleCommand =>
            createCircleCommand ?? (createCircleCommand = new DelegateCommand<DispMDrawCircle>(ExecuteCreateCircleCommand));
        private DelegateCommand calcCircleCommand;
        public DelegateCommand CalcCircleCommand =>
            calcCircleCommand ?? (calcCircleCommand = new DelegateCommand(ExecuteCalcCircleCommand));
        private DelegateCommand<DispMJudge> judgeList1SelectCommand;
        public DelegateCommand<DispMJudge> JudgeList1SelectCommand =>
            judgeList1SelectCommand ?? (judgeList1SelectCommand = new DelegateCommand<DispMJudge>(ExecuteJudgeList1SelectCommand));
        private DelegateCommand<DispMJudge> updateDistCommand;
        public DelegateCommand<DispMJudge> UpdateDistCommand =>
            updateDistCommand ?? (updateDistCommand = new DelegateCommand<DispMJudge>(ExecuteUpdateDistCommand));
        private DelegateCommand calcDistCommand;
        public DelegateCommand CalcDistCommand =>
            calcDistCommand ?? (calcDistCommand = new DelegateCommand(ExecuteCalcDistCommand));
        private DelegateCommand<object> textBoxLostFocusEventCommand;
        public DelegateCommand<object> TextBoxLostFocusEventCommand =>
            textBoxLostFocusEventCommand ?? (textBoxLostFocusEventCommand = new DelegateCommand<object>(ExecuteTextBoxLostFocusEventCommand));

        void ExecuteTextBoxLostFocusEventCommand(object obj)
        {
            string filepath = $"Camera\\{cameraIndex}";
            try
            {
                switch (obj.ToString())
                {
                    case "ModelThresholdMax":
                        HOperatorSet.WriteTuple(new HTuple(ModelThresholdMax), System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "ModelThresholdMax.tup"));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
        void ExecuteCalcDistCommand()
        {
            if (CameraIamge0 != null)
            {
                string filepath = $"Camera\\{cameraIndex}";
                CameraAppendHMessage0 = null;
                CameraAppendHObject0 = null;
                mJudgeCalcList.Clear();
                try
                {
                    HObject rec1_region;
                    HOperatorSet.ReadRegion(out rec1_region, System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "rec1_Region.hobj"));
                    HObject ho_ResultRegion;
                    HTuple hv_Row, hv_Column;
                    ImageCalc.FindModel(CameraIamge0, rec1_region, ModelThresholdMax, out ho_ResultRegion, out hv_Row, out hv_Column);

                    CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                    CameraGCStyle0 = new Tuple<string, object>("Color", "yellow");

                    CameraAppendHObject0 = rec1_region;

                    if (hv_Row.D != 0)
                    {
                        CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                        CameraGCStyle0 = new Tuple<string, object>("Color", "magenta");
                        CameraAppendHObject0 = ho_ResultRegion;
                        HTuple ST_Row, ST_Column;
                        HOperatorSet.ReadTuple(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "ST_Row.tup"), out ST_Row);
                        HOperatorSet.ReadTuple(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "ST_Column.tup"), out ST_Column);

                        HTuple HomMat2D;
                        HOperatorSet.VectorAngleToRigid(ST_Row, ST_Column, 0, hv_Row, hv_Column, 0, out HomMat2D);
                        bool totalResult = true;
                        CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                        foreach (var item in CircleList1)
                        {
                            HTuple row1, column1;
                            HOperatorSet.AffineTransPoint2d(HomMat2D, item.Row, item.Column, out row1, out column1);//偏置后的圆心位置
                            HTuple hv_ResutlRow, hv_ResultColumn, hv_ResultRadius;
                            ImageCalc.FindCircle(CameraIamge0, row1, column1, item.Radius, item.MeasureThrehold,
                                out hv_ResutlRow, out hv_ResultColumn, out hv_ResultRadius);
                            if (hv_ResutlRow != null)
                            {
                                HObject ho_ResultCircle;
                                HOperatorSet.GenCircle(out ho_ResultCircle, hv_ResutlRow, hv_ResultColumn, hv_ResultRadius);
                                CameraGCStyle0 = new Tuple<string, object>("Color", "cyan");
                                CameraAppendHObject0 = ho_ResultCircle;
                                mJudgeCalcList.Add(new MJudgeCalc { 
                                    PcsOrder = item.PcsOrder,
                                    Row = hv_ResutlRow,
                                    Column = hv_ResultColumn
                                });
                            }
                        }

                        if (mJudgeCalcList.Any())
                        {
                            foreach (var item in JudgeList1)
                            {
                                var circle0 = mJudgeCalcList.FirstOrDefault(j => j.PcsOrder == item.CircleIndex0);
                                var circle1 = mJudgeCalcList.FirstOrDefault(j => j.PcsOrder == item.CircleIndex1);
                                if (circle0 != null && circle1 != null)
                                {
                                    HTuple dist;
                                    HOperatorSet.DistancePp(circle0.Row,circle0.Column,circle1.Row,circle1.Column,out dist);
                                    HObject line;
                                    HOperatorSet.GenRegionLine(out line, circle0.Row, circle0.Column, circle1.Row, circle1.Column);
                                    if (dist.D >= item.ST_DistMin && dist.D <= item.ST_DistMax)
                                    {
                                        CameraGCStyle0 = new Tuple<string, object>("Color", "green");
                                       // CameraAppendHMessage0 = new HMsgEntry($"{dist.D:f1}", (int)((circle0.Row + circle1.Row) / 2), (int)((circle0.Column + circle1.Column) / 2), "green", "image", "box", "false", 14, "mono", "true", "false");
                                    }
                                    else
                                    {
                                        CameraGCStyle0 = new Tuple<string, object>("Color", "red");
                                        CameraAppendHMessage0 = new HMsgEntry($"{dist.D:f1}", (int)((circle0.Row + circle1.Row) / 2), (int)((circle0.Column + circle1.Column) / 2), "red", "image", "box", "false", 14, "mono", "true", "false");
                                        totalResult = false;
                                    }
                                    CameraAppendHObject0 = line;
                                }
                                else
                                {
                                    totalResult = false;
                                }
                            }
                        }
                        else
                        {
                            totalResult = false;
                        }
                        if (totalResult)
                        {
                            CameraAppendHMessage0 = new HMsgEntry("OK", 10, 10, "green", "window", "box", "false", 32, "mono", "true", "false");
                        }
                        else
                        {
                            CameraAppendHMessage0 = new HMsgEntry("NG", 10, 10, "red", "window", "box", "false", 32, "mono", "true", "false");
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("图像为空！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteUpdateDistCommand(DispMJudge dist)
        {
            if (dist != null)
            {
                using var mdb = new MDbContext();
                var _dist0 = mdb.MJudges.FirstOrDefault(p => p.PcsOrder == dist.PcsOrder && p.Kind == cameraIndex);
                if (_dist0 != null)
                {
                    _dist0.CircleIndex0 = dist.CircleIndex0 = CircleIndex0;
                    _dist0.CircleIndex1 = dist.CircleIndex1 = CircleIndex1;
                    _dist0.ST_DistMin = dist.ST_DistMin = ST_DistMin;
                    _dist0.ST_DistMax = dist.ST_DistMax = ST_DistMax;
                    mdb.SaveChanges();
                }
            }
            else
            {
                MessageBox.Show("未选择任何栏目！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteJudgeList1SelectCommand(DispMJudge dist)
        {
            if (dist != null)
            {
                CircleIndex0 = dist.CircleIndex0;
                CircleIndex1 = dist.CircleIndex1;
                ST_DistMin = dist.ST_DistMin;
                ST_DistMax = dist.ST_DistMax;
            }
        }
        void ExecuteCalcCircleCommand()
        {

            if (CameraIamge0 != null)
            {
                string filepath = $"Camera\\{cameraIndex}";
                CameraAppendHMessage0 = null;
                CameraAppendHObject0 = null;
                try
                {
                    HObject rec1_region;
                    HOperatorSet.ReadRegion(out rec1_region, System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "rec1_Region.hobj"));
                    HObject ho_ResultRegion;
                    HTuple hv_Row, hv_Column;
                    ImageCalc.FindModel(CameraIamge0, rec1_region, ModelThresholdMax, out ho_ResultRegion, out hv_Row, out hv_Column);

                    CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                    CameraGCStyle0 = new Tuple<string, object>("Color", "yellow");

                    CameraAppendHObject0 = rec1_region;

                    if (hv_Row.D != 0)
                    {
                        CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                        CameraGCStyle0 = new Tuple<string, object>("Color", "magenta");
                        CameraAppendHObject0 = ho_ResultRegion;
                        HTuple ST_Row, ST_Column;
                        HOperatorSet.ReadTuple(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "ST_Row.tup"), out ST_Row);
                        HOperatorSet.ReadTuple(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "ST_Column.tup"), out ST_Column);

                        HTuple HomMat2D;
                        HOperatorSet.VectorAngleToRigid(ST_Row, ST_Column, 0, hv_Row, hv_Column, 0, out HomMat2D);
                        bool totalResult = true;
                        CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                        foreach (var item in CircleList1)
                        {
                            HTuple row1, column1;
                            HOperatorSet.AffineTransPoint2d(HomMat2D,item.Row,item.Column,out row1,out column1);//偏置后的圆心位置
                            HTuple hv_ResutlRow, hv_ResultColumn, hv_ResultRadius;
                            ImageCalc.FindCircle(CameraIamge0, row1, column1, item.Radius, item.MeasureThrehold,
                                out hv_ResutlRow, out hv_ResultColumn, out hv_ResultRadius);
                            if (hv_ResutlRow != null)
                            {
                                HObject ho_ResultCircle;
                                HOperatorSet.GenCircle(out ho_ResultCircle, hv_ResutlRow, hv_ResultColumn, hv_ResultRadius);
                                CameraGCStyle0 = new Tuple<string, object>("Color", "green");
                                CameraAppendHObject0 = ho_ResultCircle;
                                if (hv_ResultRadius.D < item.ST_RadiusMin || hv_ResultRadius.D > item.ST_RadiusMax)
                                {
                                    totalResult = false;
                                    CameraAppendHMessage0 = new HMsgEntry($"{item.PcsOrder}", (int)row1.D - 90, (int)column1.D - 50, "red", "image", "box", "false", 22, "mono", "true", "false");
                                }
                            }
                            else
                            {
                                HObject ho_ResultCircle;
                                HOperatorSet.GenCircle(out ho_ResultCircle, row1, column1, item.Radius);
                                CameraGCStyle0 = new Tuple<string, object>("Color", "red");
                                CameraAppendHObject0 = ho_ResultCircle;
                                totalResult = false;
                                CameraAppendHMessage0 = new HMsgEntry($"{item.PcsOrder}", (int)row1.D - 90, (int)column1.D - 50, "red", "image", "box", "false", 22, "mono", "true", "false");
                            }
                        }
                        if (totalResult)
                        {
                            CameraAppendHMessage0 = new HMsgEntry("OK", 10, 10, "green", "window", "box", "false", 32, "mono", "true", "false");
                        }
                        else
                        {
                            CameraAppendHMessage0 = new HMsgEntry("NG", 10, 10, "red", "window", "box", "false", 32, "mono", "true", "false");
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else 
            {
                MessageBox.Show("图像为空！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteCreateCircleCommand(DispMDrawCircle circle)
        {
            if (circle != null)
            {
                if (CameraIamge0 != null)
                {
                    string filepath = $"Camera\\{cameraIndex}";
                    CameraAppendHMessage0 = null;
                    CameraAppendHObject0 = null;
                    if (MessageBox.Show($"你确定画相机{cameraIndex + 1}的\"{circle.PcsOrder}\"圆吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        try
                        {
                            ROICircle roi = (ROICircle)(Global.CameraImageViewer1.DrawROI(ROI.ROI_TYPE_CIRCLE));
                            using var mdb = new MDbContext();
                            var _circle0 = mdb.MDrawCircles.FirstOrDefault(p => p.PcsOrder == circle.PcsOrder && p.Kind == cameraIndex);
                            if (_circle0 != null)
                            {
                                _circle0.Row = circle.Row = Math.Round(roi.midR, 1);
                                _circle0.Column = circle.Column = Math.Round(roi.midC, 1);
                                _circle0.Radius = circle.Radius = Math.Round(roi.radius, 1);
                                mdb.SaveChanges();
                            }
                            CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                            CameraGCStyle0 = new Tuple<string, object>("Color", "cyan");
                            CameraAppendHObject0 = roi.getRegion();
                            HTuple hv_ResutlRow, hv_ResultColumn, hv_ResultRadius;
                            ImageCalc.FindCircle(CameraIamge0, roi.midR, roi.midC, roi.radius, circle.MeasureThrehold,
                                out hv_ResutlRow,out hv_ResultColumn,out hv_ResultRadius);
                            if (hv_ResutlRow != null)
                            {
                                HObject ho_ResultCircle;
                                HOperatorSet.GenCircle(out ho_ResultCircle, hv_ResutlRow, hv_ResultColumn, hv_ResultRadius);
                                CameraGCStyle0 = new Tuple<string, object>("Color", "green");
                                CameraAppendHObject0 = ho_ResultCircle;
                                CameraAppendHMessage0 = new HMsgEntry($"R:{hv_ResutlRow.D:f1},C:{hv_ResultColumn.D:f1}", 10, 10, "spring green", "window", "box", "false", 32, "mono", "true", "false");
                                CameraAppendHMessage0 = new HMsgEntry($"半径:{hv_ResultRadius.D:f1}", 40, 10, "spring green", "window", "box", "false", 32, "mono", "true", "false");
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex);
                            MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("图像为空！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("未选择任何栏目！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteUpdateCircleCommand(DispMDrawCircle circle)
        {
            if (circle != null)
            {
                using var mdb = new MDbContext();
                var _circle0 = mdb.MDrawCircles.FirstOrDefault(p => p.PcsOrder == circle.PcsOrder && p.Kind == cameraIndex);
                if (_circle0 != null)
                {
                    _circle0.MeasureThrehold = circle.MeasureThrehold = MeasureThrehold;
                    _circle0.ST_RadiusMin = circle.ST_RadiusMin = ST_RadiusMin;
                    _circle0.ST_RadiusMax = circle.ST_RadiusMax = ST_RadiusMax;
                    mdb.SaveChanges();
                }
            }
            else
            {
                MessageBox.Show("未选择任何栏目！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteCircleList1SelectCommand(DispMDrawCircle circle)
        {
            if (circle != null)
            {
                MeasureThrehold = circle.MeasureThrehold;
                ST_RadiusMin = circle.ST_RadiusMin;
                ST_RadiusMax = circle.ST_RadiusMax;
            }
        }
        void ExecutePosImageSetStandardCommand()
        {
            if (CameraIamge0 != null)
            {
                if (MessageBox.Show($"你确定设置相机{cameraIndex + 1}的基准位置吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    string filepath = $"Camera\\{cameraIndex}";
                    try
                    {
                        HObject rec1;
                        HOperatorSet.ReadRegion(out rec1, System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "rec1_Region.hobj"));
                        HObject ho_ResultRegion;
                        HTuple hv_Row, hv_Column;
                        ImageCalc.FindModel(CameraIamge0, rec1, ModelThresholdMax, out ho_ResultRegion, out hv_Row, out hv_Column);
                        CameraAppendHMessage0 = null;
                        CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                        CameraGCStyle0 = new Tuple<string, object>("Color", "yellow");
                        CameraAppendHObject0 = null;
                        CameraAppendHObject0 = rec1;

                        if (hv_Row.D != 0)
                        {
                            CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                            CameraGCStyle0 = new Tuple<string, object>("Color", "magenta");
                            CameraAppendHObject0 = ho_ResultRegion;
                            CameraAppendHMessage0 = new HMsgEntry($"Row:{hv_Row.D:f0}", 10, 10, "turquoise", "window", "box", "false", 32, "mono", "true", "false");
                            CameraAppendHMessage0 = new HMsgEntry($"Column:{hv_Column.D:f0}", 40, 10, "turquoise", "window", "box", "false", 32, "mono", "true", "false");

                            HOperatorSet.WriteTuple(hv_Row, System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "ST_Row.tup"));
                            HOperatorSet.WriteTuple(hv_Column, System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "ST_Column.tup"));
                        }
                        else
                        {
                            CameraAppendHMessage0 = new HMsgEntry("未找到模板", 10, 10, "red", "window", "box", "false", 32, "mono", "true", "false");
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                
            }
            else
            {
                MessageBox.Show("图像为空！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecutePosImageFindModelCommand()
        {
            if (CameraIamge0 != null)
            {
                string filepath = $"Camera\\{cameraIndex}";
                try
                {
                    HObject rec1;
                    HOperatorSet.ReadRegion(out rec1, System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "rec1_Region.hobj"));
                    HObject ho_ResultRegion;
                    HTuple hv_Row, hv_Column;
                    ImageCalc.FindModel(CameraIamge0, rec1,ModelThresholdMax, out ho_ResultRegion,out hv_Row,out hv_Column);
                    CameraAppendHMessage0 = null;
                    CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                    CameraGCStyle0 = new Tuple<string, object>("Color", "yellow");
                    CameraAppendHObject0 = null;
                    CameraAppendHObject0 = rec1;

                    if (hv_Row.D != 0)
                    {
                        CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                        CameraGCStyle0 = new Tuple<string, object>("Color", "magenta");
                        CameraAppendHObject0 = ho_ResultRegion;
                        CameraAppendHMessage0 = new HMsgEntry($"Row:{hv_Row.D:f0}", 10, 10, "turquoise", "window", "box", "false", 32, "mono", "true", "false");
                        CameraAppendHMessage0 = new HMsgEntry($"Column:{hv_Column.D:f0}", 40, 10, "turquoise", "window", "box", "false", 32, "mono", "true", "false");
                    }
                    else
                    {
                        CameraAppendHMessage0 = new HMsgEntry("未找到模板", 10, 10, "red", "window", "box", "false", 32, "mono", "true", "false");
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("图像为空！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecutePosImageCreateRegionCommand()
        {
            if (CameraIamge0 != null)
            {
                string filepath = $"Camera\\{cameraIndex}";
                if (MessageBox.Show($"你确定画相机{cameraIndex + 1}的定位区域吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    try
                    {
                        var roi = Global.CameraImageViewer1.DrawROI(ROI.ROI_TYPE_RECTANGLE1);
                        var rec1 = roi.getRegion();

                        DirectoryInfo dir = new DirectoryInfo(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath));
                        if (!dir.Exists)
                        {
                            Directory.CreateDirectory(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath));
                        }
                        HOperatorSet.WriteRegion(rec1, System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "rec1_Region.hobj"));
                        CameraAppendHMessage0 = null;
                        CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                        CameraGCStyle0 = new Tuple<string, object>("Color", "yellow");
                        CameraAppendHObject0 = null;
                        CameraAppendHObject0 = rec1;
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                MessageBox.Show("图像为空！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteCalcCommand()
        {
            if (CameraIamge0 != null)
            {
                string filepath = $"Camera\\{cameraIndex}";
                CameraAppendHMessage0 = null;
                CameraAppendHObject0 = null;
                try
                {
                    HObject rec1_region;
                    HOperatorSet.ReadRegion(out rec1_region, System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "rec1_Region.hobj"));
                    HObject ho_ResultRegion;
                    HTuple hv_Row, hv_Column;
                    ImageCalc.FindModel(CameraIamge0, rec1_region, ModelThresholdMax, out ho_ResultRegion, out hv_Row, out hv_Column);

                    CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                    CameraGCStyle0 = new Tuple<string, object>("Color", "yellow");
        
                    CameraAppendHObject0 = rec1_region;

                    if (hv_Row.D != 0)
                    {
                        CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                        CameraGCStyle0 = new Tuple<string, object>("Color", "magenta");
                        CameraAppendHObject0 = ho_ResultRegion;
                        HTuple ST_Row,ST_Column;
                        HOperatorSet.ReadTuple(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "ST_Row.tup"),out ST_Row);
                        HOperatorSet.ReadTuple(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "ST_Column.tup"), out ST_Column);

                        HTuple HomMat2D;
                        HOperatorSet.VectorAngleToRigid(ST_Row, ST_Column, 0, hv_Row, hv_Column, 0, out HomMat2D);

                        bool totalResult = true;
                        foreach (var item in PointList1)
                        {
                            HObject rec1_1;
                            HOperatorSet.ReadRegion(out rec1_1, System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, $"rec1_{item.PcsOrder}.hobj"));
                            HObject rec1;
                            HOperatorSet.AffineTransRegion(rec1_1,out rec1, HomMat2D, "nearest_neighbor");
                            rec1_1.Dispose();
                  
                            HObject ho_resultRegion; HTuple hv_result, mArea;
                            ImageCalc.AreaCalc(CameraIamge0, rec1, item.ThresholdMin, item.ThresholdMax, item.JudgeArea, out ho_resultRegion, out hv_result, out mArea);
                            
                            HTuple msgRow, mesColumn;
                            HOperatorSet.RegionFeatures(rec1, "row", out msgRow);
                            HOperatorSet.RegionFeatures(rec1, "column", out mesColumn);
                            CameraAppendHMessage0 = new HMsgEntry($"{item.PcsOrder}", (int)msgRow.D, (int)mesColumn.D, "black", "image", "box", "true", 12, "mono", "true", "false");
                            if (hv_result == 1)
                            {
                                CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                                CameraGCStyle0 = new Tuple<string, object>("Color", "green");
                                CameraAppendHObject0 = ho_resultRegion;
                            }
                            else
                            {
                                totalResult = false;
                                CameraGCStyle0 = new Tuple<string, object>("Color", "red");
                                CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                                CameraAppendHObject0 = rec1;
                            }
                            
                        }
                        if (totalResult)
                        {
                            CameraAppendHMessage0 = new HMsgEntry("OK", 10, 10, "green", "window", "box", "false", 32, "mono", "true", "false");
                        }
                        else
                        {
                            CameraAppendHMessage0 = new HMsgEntry("NG", 10, 10, "red", "window", "box", "false", 32, "mono", "true", "false");
                        }
                    }
                    else
                    {
                        CameraAppendHMessage0 = new HMsgEntry("未找到模板", 10, 10, "red", "window", "box", "false", 32, "mono", "true", "false");
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("图像为空！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }


        }
        void ExecuteUpdateCommand(DispVisionPoint2 point)
        {
            if (point != null)
            {
                using var mdb = new MDbContext();
                var _point0 = mdb.MVisionPoint2s.FirstOrDefault(p => p.PcsOrder == point.PcsOrder && p.Kind == cameraIndex);
                if (_point0 != null)
                {
                    _point0.ThresholdMin = point.ThresholdMin = ThresholdMin;
                    _point0.ThresholdMax = point.ThresholdMax = ThresholdMax;
                    _point0.JudgeArea = point.JudgeArea = JudgeArea;
                    mdb.SaveChanges();
                }
            }
            else
            {
                MessageBox.Show("未选择任何栏目！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecuteCreateRec1Command(DispVisionPoint2 point)
        {
            if (point != null)
            {
                if (CameraIamge0 != null)
                {
                    string filepath = $"Camera\\{cameraIndex}";
                    if (MessageBox.Show($"你确定画相机{cameraIndex + 1}的\"{point.PcsOrder}\"区域吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        try
                        {
                            var roi = Global.CameraImageViewer1.DrawROI(ROI.ROI_TYPE_RECTANGLE1);
                            var rec1 = roi.getRegion();

                            DirectoryInfo dir = new DirectoryInfo(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath));
                            if (!dir.Exists)
                            {
                                Directory.CreateDirectory(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath));
                            }
                            HOperatorSet.WriteRegion(rec1, System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, $"rec1_{point.PcsOrder}.hobj"));
                            CameraAppendHMessage0 = null;
                            CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                            CameraGCStyle0 = new Tuple<string, object>("Color", "orange red");
                            CameraAppendHObject0 = null;
                            CameraAppendHObject0 = rec1;
                            HObject ho_resultRegion; HTuple hv_result, mArea;
                            ImageCalc.AreaCalc(CameraIamge0, rec1, point.ThresholdMin, point.ThresholdMax, point.JudgeArea, out ho_resultRegion, out hv_result, out mArea);
                            CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                            CameraAppendHMessage0 = new HMsgEntry($"{mArea.D:f0}", 40, 10, "medium blue", "window", "box", "false", 32, "mono", "true", "false");
                            if (hv_result == 1)
                            {
                                CameraAppendHMessage0 = new HMsgEntry("OK", 10, 10, "green", "window", "box", "false", 32, "mono", "true", "false");
                                CameraGCStyle0 = new Tuple<string, object>("Color", "green");
                            }
                            else
                            {
                                CameraAppendHMessage0 = new HMsgEntry("NG", 10, 10, "red", "window", "box", "false", 32, "mono", "true", "false");
                                CameraGCStyle0 = new Tuple<string, object>("Color", "red");
                            }
                            CameraAppendHObject0 = ho_resultRegion;
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex);
                            MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("图像为空！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("未选择任何栏目！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void ExecutePointList1SelectCommand(DispVisionPoint2 point)
        {
            if (point != null)
            {
                ThresholdMin = point.ThresholdMin;
                ThresholdMax = point.ThresholdMax;
                JudgeArea = point.JudgeArea;
            }
        }
        void ExecuteCameraOperateCommand(object obj)
        {
            switch (obj.ToString())
            {
                case "拍照":
                    CameraIamge0 = cam.GrabImage();
                    //try
                    //{
                    //    HObject ho_ImageRotate;
                    //    var img = cam.GrabeImageAsync();
                    //    if (img != null)
                    //    {
                    //        HOperatorSet.RotateImage(img, out ho_ImageRotate, RotateDeg, "constant");
                    //        CameraIamge0 = new HImage(ho_ImageRotate);
                    //    }
                    //}
                    //catch (Exception ex)
                    //{
                    //    Console.WriteLine(ex.Message);
                    //}

                    break;
                case "打开":
                    {
                        OpenFileDialog openFileDialog = new OpenFileDialog();
                        openFileDialog.Filter = "Image Files|*.png;*.bmp;*.jpg;*.tif";
                        if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            HObject image;
                            HOperatorSet.ReadImage(out image, openFileDialog.FileName);
                            CameraIamge0 = new HImage(image);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
        #endregion
        #region 导航
        public override void OnDialogOpened(IDialogParameters parameters)
        {
            cameraIndex = parameters.GetValue<int>("CameraIndex");
            Title = $"相机{cameraIndex + 1}";
            switch (cameraIndex)
            {
                case 2:
                    cam = _containerProvider.Resolve<ICameraService>("Cam2");
                    break;
                case 3:
                    cam = _containerProvider.Resolve<ICameraService>("Cam3");
                    break;
                default:
                    break;
            }
            string filepath = $"Camera\\{cameraIndex}";
            try
            {
                HTuple v1;
                HOperatorSet.ReadTuple(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filepath, "ModelThresholdMax.tup"), out v1);
                ModelThresholdMax = v1.D;
            }
            catch { }
            using var mdb = new MDbContext();
            var points0 = mdb.MVisionPoint2s.Where(p => p.Kind == cameraIndex);
            if (points0.Any())
            {
                var points1 = points0.OrderBy(p => p.PcsOrder).ToList();
                foreach (var item in points1)
                {
                    PointList1.Add(new DispVisionPoint2
                    {
                        PcsOrder = item.PcsOrder,
                        ThresholdMax = item.ThresholdMax,
                        ThresholdMin = item.ThresholdMin,
                        JudgeArea = item.JudgeArea
                    });
                }
            }
            var drawcircle0 = mdb.MDrawCircles.Where(p => p.Kind == cameraIndex);
            if (drawcircle0.Any())
            {
                var drawcircle1 = drawcircle0.OrderBy(p => p.PcsOrder).ToList();
                foreach (var item in drawcircle1)
                {
                    CircleList1.Add(new DispMDrawCircle
                    {
                        PcsOrder = item.PcsOrder,
                        Row = item.Row,
                        Column= item.Column,
                        Radius= item.Radius,
                        MeasureThrehold= item.MeasureThrehold,
                        ST_RadiusMax = item.ST_RadiusMax,
                        ST_RadiusMin = item.ST_RadiusMin,
                    });
                }
            }
            var judge0 = mdb.MJudges.Where(p => p.Kind == cameraIndex);
            if (judge0.Any())
            {
                var judge1 = judge0.OrderBy(p => p.PcsOrder).ToList();
                foreach (var item in judge1)
                {
                    JudgeList1.Add(new DispMJudge 
                    {
                        PcsOrder = item.PcsOrder,
                        CircleIndex0 = item.CircleIndex0,
                        CircleIndex1= item.CircleIndex1,
                        ST_DistMax= item.ST_DistMax,
                        ST_DistMin= item.ST_DistMin
                    });
                }
            }
        }
        #endregion
        #region 构造函数
        public Station2CameraCalcDialogViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            _containerProvider = containerProvider;
            PointList1 = new ObservableCollection<DispVisionPoint2>();
            CircleList1 = new ObservableCollection<DispMDrawCircle>();
            JudgeList1 = new ObservableCollection<DispMJudge>();
        }
        #endregion
    }
}
